package nsqp

import (
	"bgs/conf"
	"bgs/db"
	"bgs/grpc/imp/enums"
	"bgs/nsqp/topic"
	"bgs/nsqp/util"
	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

// ForwardProxy proxy forwarding nsq message
type ForwardProxy struct {
	dao  *db.PgDao
	slog *zap.SugaredLogger
	subs []*nsq.Consumer
}

// NewGsmsProxy initialization
func NewForwardProxy(nsqConf conf.NsqSection, pgdao *db.PgDao, slog *zap.SugaredLogger) (proxy *ForwardProxy, err error) {
	config := nsq.NewConfig()
	producer, err := nsq.NewProducer(nsqConf.NsqdAddress, config)
	if err != nil {
		return
	}
	proxy = &ForwardProxy{
		dao:  pgdao,
		slog: slog,
	}

	// 1: bgs-order_update => inventory-order_notify
	fromTopics := []string{
		topic.Make(enums.APPIDBGS)(topicOfOrderUpdateToInventory),
	}
	toTopics := []string{
		topic.Make(enums.APPIDINVENTORY)(topicOfOrderNotifyToInventory),
	}

	for idx, topicFrom := range fromTopics {
		topicTo := toTopics[idx]
		slog.Infof("topicFrom:%s,topicTo:%s", topicFrom, topicTo)
		consumer, err2 := nsq.NewConsumer(topicFrom, appID, config)
		if err2 != nil {
			err = err2
			return
		}
		consumer.SetLogger(nsqLogger, nsq.LogLevelError)
		consumer.AddHandler(util.NewNsqForwarder(pgdao, slog, producer, topicFrom, topicTo))
		err = consumer.ConnectToNSQLookupd(nsqConf.NsqLookupds[0])
		if err != nil {
			return
		}
		proxy.subs = append(proxy.subs, consumer)
	}
	return
}
